/**
 * ReportGear(2011)
 */
package com.reportgear.report.model.calculator;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.reportgear.core.data.SalaryHelper;
import com.reportgear.core.data.model.SalaryDataObject;
import com.reportgear.report.model.ReportModel;
import com.reportgear.report.model.cell.Cell;
import com.reportgear.report.model.cell.value.MainDetailObject;
import com.reportgear.report.model.cell.value.salary.SalaryDetailObject;

/**
 * 
 * 工资明细对象计算，扩展工资明细对象
 * 
 * @version 1.0 2011-6-6
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public class MainDetailObjectCalculator extends AbstractCalculator {
	public MainDetailObjectCalculator() {

	}

	@Override
	public ReportModel calculate(ReportModel model, CalcParameter parameter) {
		if (logger.isDebugEnabled()) {
			logger.debug("计算模型：工资明细对象计算");
		}

		ReportModel calcModel = model;

		this.doCalculate(calcModel, parameter);

		return calcModel;
	}

	/**
	 * 计算
	 * 
	 * @param model
	 *            模型
	 */
	private void doCalculate(ReportModel model, CalcParameter parameter) {
		Iterator<Cell> iter = model.getCellsIteratorByCellElementClass(SalaryDetailObject.class);
		for (Iterator<Cell> i = iter; i.hasNext();) {
			this.calculateCell(model, i.next(), parameter);
		}
	}

	/**
	 * 计算单元格<br/>
	 * 从当前行开始生成SalaryMainObject<br/>
	 * 当前行改变，其它插入,插入行时复制上一行的style
	 * 
	 * @param model
	 *            模型
	 * @param cell
	 *            单元格
	 */
	private void calculateCell(ReportModel model, Cell cell, CalcParameter parameter) {
		Set<Integer> colSet = new HashSet<Integer>();
		colSet.add(-1);
		List<SalaryDataObject> dataList = SalaryHelper.INSTANCE.getPayDoc(parameter.getPaymentId(), parameter
				.getSalaryObjectType(), parameter.getMaxLevel(), parameter.getSelectObjSet(), colSet);

		List<MainDetailObject> roList = new ArrayList<MainDetailObject>();
		SalaryDetailObject detail = (SalaryDetailObject) cell.getValue();
		for (SalaryDataObject sdo : dataList) {
			MainDetailObject mdo = new MainDetailObject(sdo.getInt("objectID"), sdo.getString(detail.getField()));

			roList.add(mdo);
		}

		int row = cell.getRow();
		int col = cell.getColumn();
		int ptr = row;

		for (MainDetailObject smo : roList) {
			if (ptr != row) {
				model.addRow(ptr);
				model.copyRowProperties(ptr, ptr - 1);
			}

			model.setCellValue(col, ptr, smo);
			ptr++;
		}
	}
}
